<template>
  <ion-page>
    <ion-header :translucent="true">
      <ion-toolbar>
        <ion-buttons slot="start">
          <ion-back-button default-href="/tabs/profile"></ion-back-button>
        </ion-buttons>
        <ion-title>活跃度排行榜</ion-title>
        <ion-buttons slot="end">
          <ion-button @click="showRules" fill="clear">
            <ion-icon :icon="helpCircleOutline"></ion-icon>
          </ion-button>
        </ion-buttons>
      </ion-toolbar>
    </ion-header>

    <ion-content :fullscreen="true">
      <!-- 活跃度规则按钮 -->
      <div class="rules-button-section">
        <ion-button
          expand="block"
          fill="outline"
          @click="goToRules"
          class="rules-button"
        >
          <ion-icon :icon="documentTextOutline" slot="start"></ion-icon>
          活跃度规则
        </ion-button>
      </div>

      <!-- 签到状态卡片 -->
      <ion-card class="checkin-card">
        <ion-card-content>
          <div class="checkin-header">
            <h2>已累计签到</h2>
            <ion-button 
              @click="checkIn" 
              :disabled="hasCheckedInToday"
              :color="hasCheckedInToday ? 'medium' : 'primary'"
              class="checkin-btn"
            >
              {{ hasCheckedInToday ? '今日已签到' : '签到' }}
            </ion-button>
          </div>
          
          <div class="checkin-stats">
            <div class="stat-item">
              <div class="stat-number">{{ userStats.consecutiveDays }}</div>
              <div class="stat-label">天</div>
            </div>
            <div class="stat-divider"></div>
            <div class="stat-description">
              <p>累计活跃度: {{ userStats.totalPoints }}</p>
            </div>
          </div>
          

        </ion-card-content>
      </ion-card>

      <!-- 排行榜 -->
      <div class="ranking-section">
        <!-- 前三名展示 -->
        <div class="top-three">
          <!-- 第二名 -->
          <div class="rank-item rank-2">
            <div class="crown">
              <ion-icon :icon="medalOutline" color="medium"></ion-icon>
            </div>
            <div class="avatar">
              <ion-icon :icon="personCircleOutline" size="large"></ion-icon>
            </div>
            <div class="rank-badge">NO.2</div>
            <div class="user-name">家天下房产 李三</div>
            <div class="points">{{ topUsers[1]?.points || 400 }}</div>
          </div>

          <!-- 第一名 -->
          <div class="rank-item rank-1">
            <div class="crown">
              <ion-icon :icon="trophyOutline" color="warning"></ion-icon>
            </div>
            <div class="avatar">
              <ion-icon :icon="personCircleOutline" size="large"></ion-icon>
            </div>
            <div class="rank-badge champion">NO.1</div>
            <div class="user-name">家天下房产 张三</div>
            <div class="points">{{ topUsers[0]?.points || 500 }}</div>
          </div>

          <!-- 第三名 -->
          <div class="rank-item rank-3">
            <div class="crown">
              <ion-icon :icon="medalOutline" color="tertiary"></ion-icon>
            </div>
            <div class="avatar">
              <ion-icon :icon="personCircleOutline" size="large"></ion-icon>
            </div>
            <div class="rank-badge">NO.3</div>
            <div class="user-name">家天下房产 王五</div>
            <div class="points">{{ topUsers[2]?.points || 300 }}</div>
          </div>
        </div>

        <!-- 排行榜列表 -->
        <div class="ranking-list">
          <div 
            v-for="(user, index) in rankingList" 
            :key="user.id"
            class="ranking-item"
            :class="{ 'current-user': user.isCurrentUser }"
          >
            <div class="rank-number">NO.{{ index + 4 }}</div>
            <div class="user-info">
              <div class="user-name">{{ user.name }}</div>
              <div class="user-company">{{ user.company }}</div>
            </div>
            <div class="user-points">
              <ion-icon :icon="medalOutline" color="medium"></ion-icon>
              {{ user.points }}
            </div>
          </div>
        </div>
      </div>
    </ion-content>
  </ion-page>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import {
  IonPage,
  IonHeader,
  IonToolbar,
  IonTitle,
  IonContent,
  IonButtons,
  IonButton,
  IonBackButton,
  IonIcon,
  IonCard,
  IonCardContent,
  alertController,
  toastController
} from '@ionic/vue'
import {
  helpCircleOutline,
  personCircleOutline,
  trophyOutline,
  medalOutline,
  documentTextOutline
} from 'ionicons/icons'
import { useUserStore } from '@/stores/user'

interface User {
  id: number
  name: string
  company: string
  points: number
  isCurrentUser?: boolean
}

const router = useRouter()
const userStore = useUserStore()

// 用户签到状态
const hasCheckedInToday = ref(false)
const userStats = ref({
  consecutiveDays: 3,
  totalPoints: 30
})

// 前三名用户
const topUsers = ref([
  { id: 1, name: '张三', company: '家天下房产', points: 500 },
  { id: 2, name: '李三', company: '家天下房产', points: 400 },
  { id: 3, name: '王五', company: '家天下房产', points: 300 }
])

// 排行榜列表（第4名及以后）
const rankingList = ref<User[]>([
  { id: 4, name: '王传', company: '家天下房产', points: 200 },
  { id: 5, name: '可爱房产经纪公司', company: '李白', points: 190 },
  { id: 6, name: '张成', company: '家天下房产', points: 180 },
  { id: 7, name: '张雅雯', company: '可爱房产经纪公司', points: 170 },
  { id: 8, name: '李英东', company: '家天下房产', points: 160 },
  { id: 9, name: '王天天', company: '可爱房产经纪公司', points: 150 }
])

onMounted(() => {
  // 检查今日是否已签到
  checkTodayCheckInStatus()
  // 标记当前用户在排行榜中的位置
  markCurrentUser()
})

// 检查今日签到状态
const checkTodayCheckInStatus = () => {
  const today = new Date().toDateString()
  const lastCheckIn = localStorage.getItem('lastCheckInDate')
  hasCheckedInToday.value = lastCheckIn === today
}

// 标记当前用户
const markCurrentUser = () => {
  // 假设当前用户是王传
  const currentUserIndex = rankingList.value.findIndex(user => user.name === '王传')
  if (currentUserIndex !== -1) {
    rankingList.value[currentUserIndex].isCurrentUser = true
  }
}

// 签到功能
const checkIn = async () => {
  if (hasCheckedInToday.value) return

  try {
    // 更新签到状态
    hasCheckedInToday.value = true
    userStats.value.consecutiveDays += 1
    userStats.value.totalPoints += 10

    // 保存签到日期
    const today = new Date().toDateString()
    localStorage.setItem('lastCheckInDate', today)

    // 显示签到成功提示
    const toast = await toastController.create({
      message: '签到成功！获得10活跃度',
      duration: 2000,
      color: 'success',
      position: 'top'
    })
    await toast.present()
  } catch (error) {
    console.error('签到失败:', error)
    const toast = await toastController.create({
      message: '签到失败，请重试',
      duration: 2000,
      color: 'danger',
      position: 'top'
    })
    await toast.present()
  }
}

// 跳转到活跃度规则页面
const goToRules = () => {
  router.push('/activity-rules')
}

// 显示规则说明
const showRules = async () => {
  const alert = await alertController.create({
    header: '活跃度规则',
    message: `
      <div style="text-align: left;">
        <p><strong>获得活跃度的方式：</strong></p>
        <ul>
          <li>每日签到：+10分</li>
          <li>发布房源：+20分</li>
          <li>完成租赁：+50分</li>
          <li>获得好评：+15分</li>
        </ul>
        <p><strong>排行榜更新：</strong></p>
        <p>每日凌晨更新排行榜数据</p>
      </div>
    `,
    buttons: ['知道了']
  })
  await alert.present()
}
</script>

<style scoped>
.rules-button-section {
  padding: 16px;
  padding-bottom: 8px;
}

.rules-button {
  --border-radius: 12px;
  --border-width: 2px;
  --border-style: dashed;
  --border-color: var(--ion-color-primary);
  --color: var(--ion-color-primary);
  font-weight: 600;
}

.checkin-card {
  margin: 16px;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
}

.checkin-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.checkin-header h2 {
  margin: 0;
  font-size: 18px;
  font-weight: 600;
}

.checkin-btn {
  --border-radius: 20px;
  height: 36px;
}

.checkin-stats {
  display: flex;
  align-items: center;
  gap: 16px;
}

.stat-item {
  text-align: center;
}

.stat-number {
  font-size: 32px;
  font-weight: bold;
  line-height: 1;
}

.stat-label {
  font-size: 14px;
  opacity: 0.9;
}

.stat-divider {
  width: 1px;
  height: 40px;
  background: rgba(255, 255, 255, 0.3);
}

.stat-description p {
  margin: 0;
  font-size: 14px;
  opacity: 0.9;
}

.calendar-icon {
  position: absolute;
  top: 16px;
  right: 16px;
  opacity: 0.3;
}

.ranking-section {
  padding: 0 16px 16px;
}

.top-three {
  display: flex;
  justify-content: center;
  align-items: end;
  gap: 8px;
  margin-bottom: 24px;
  padding: 0 16px;
}

.rank-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  text-align: center;
  position: relative;
}

.rank-1 {
  order: 2;
  transform: scale(1.1);
}

.rank-2 {
  order: 1;
}

.rank-3 {
  order: 3;
}

.crown {
  margin-bottom: 8px;
}

.avatar {
  width: 50px;
  height: 50px;
  border-radius: 50%;
  background: var(--ion-color-light);
  display: flex;
  align-items: center;
  justify-content: center;
  margin-bottom: 8px;
}

.rank-badge {
  background: var(--ion-color-medium);
  color: white;
  padding: 4px 8px;
  border-radius: 12px;
  font-size: 12px;
  font-weight: bold;
  margin-bottom: 4px;
}

.rank-badge.champion {
  background: var(--ion-color-warning);
}

.rank-2 .rank-badge {
  background: var(--ion-color-medium);
}

.rank-3 .rank-badge {
  background: var(--ion-color-tertiary);
}

.user-name {
  font-size: 12px;
  font-weight: 600;
  margin-bottom: 4px;
  max-width: 80px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.points {
  font-size: 14px;
  font-weight: bold;
  color: var(--ion-color-primary);
}

.ranking-list {
  background: white;
  border-radius: 12px;
  overflow: hidden;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.ranking-item {
  display: flex;
  align-items: center;
  padding: 16px;
  border-bottom: 1px solid var(--ion-color-light);
}

.ranking-item:last-child {
  border-bottom: none;
}

.ranking-item.current-user {
  background: rgba(var(--ion-color-primary-rgb), 0.1);
}

.rank-number {
  font-weight: bold;
  color: var(--ion-color-medium);
  margin-right: 16px;
  min-width: 40px;
}

.user-info {
  flex: 1;
}

.user-info .user-name {
  font-weight: 600;
  color: var(--ion-color-dark);
  margin-bottom: 2px;
  max-width: none;
  white-space: normal;
}

.user-info .user-company {
  font-size: 12px;
  color: var(--ion-color-medium);
}

.user-points {
  display: flex;
  align-items: center;
  gap: 4px;
  font-weight: bold;
  color: var(--ion-color-primary);
}
</style>
